<template>
  <div class="custom-dropdown" v-click-outside="closeDropdown">
    <div
      class="dropdown-trigger"
      :class="{ 'is-active': isOpen, 'is-disabled': disabled }"
      @click="toggleDropdown"
    >
      <div class="selected-text">
        <span v-if="multiple && selectedCount > 0" class="selected-info">
          已选择 {{ selectedCount }} 项
        </span>
        <span v-else-if="!multiple && selectedLabel">{{ selectedLabel }}</span>
        <span v-else class="placeholder">{{ placeholder }}</span>
      </div>
      <div class="dropdown-icon">
        <div class="arrow-down" :class="{ 'is-rotate': isOpen }"></div>
      </div>
    </div>

    <div class="dropdown-menu" v-show="isOpen">
      <!-- 多选模式下的操作栏 -->
      <div v-if="multiple && options.length > 0" class="dropdown-toolbar">
        <span
          class="toolbar-btn select-all"
          @click="selectAll"
          v-if="selectedCount < options.length"
        >
          全选
        </span>
        <span
          class="toolbar-btn clear-all"
          @click="clearAll"
          v-if="selectedCount > 0"
        >
          清空
        </span>
      </div>

      <div
        v-for="item in options"
        :key="item.value"
        class="dropdown-item"
        :class="{
          'is-active': multiple
            ? isItemSelected(item.value)
            : modelValue === item.value,
        }"
        @click="selectOption(item)"
      >
        <div class="item-content">
          <!-- 多选模式：显示checkbox -->
          <div v-if="multiple" class="item-checkbox">
            <div
              class="checkbox-wrapper"
              :class="{ 'is-checked': isItemSelected(item.value) }"
            >
              <div v-if="isItemSelected(item.value)" class="check-mark"></div>
            </div>
          </div>
          <!-- 单选模式：显示radio dot -->
          <div
            v-else-if="!multiple && modelValue === item.value"
            class="item-dot"
          >
            <div class="item-dot-inner"></div>
          </div>
          <span class="item-label">{{ item.label }}</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: "CustomDropdown",
  props: {
    // 支持v-model绑定的值
    modelValue: {
      type: [String, Number, Array],
      default: "",
    },
    // 下拉选项列表
    options: {
      type: Array,
      default: () => [],
    },
    // 占位文本
    placeholder: {
      type: String,
      default: "请选择",
    },
    // 是否禁用
    disabled: {
      type: Boolean,
      default: false,
    },
    // 是否为多选模式
    multiple: {
      type: Boolean,
      default: false,
    },
  },
  emits: ["update:modelValue", "change"],
  data () {
    return {
      isOpen: false,
    };
  },
  computed: {
    // 获取选中项的标签文本（单选模式）
    selectedLabel () {
      if (this.multiple) return "";
      const selected = this.options.find(
        (item) => item.value === this.modelValue,
      );
      return selected ? selected.label : "";
    },

    // 选中的数量（多选模式）
    selectedCount () {
      if (!this.multiple) return 0;
      return Array.isArray(this.modelValue) ? this.modelValue.length : 0;
    },

    // 选中的值数组（多选模式）
    selectedValues () {
      if (!this.multiple) return [];
      return Array.isArray(this.modelValue) ? this.modelValue : [];
    },
  },
  directives: {
    // 点击外部关闭下拉菜单
    "click-outside": {
      mounted (el, binding) {
        el._clickOutside = (event) => {
          if (!(el === event.target || el.contains(event.target))) {
            binding.value(event);
          }
        };
        document.addEventListener("click", el._clickOutside);
      },
      unmounted (el) {
        document.removeEventListener("click", el._clickOutside);
      },
    },
  },
  methods: {
    // 切换下拉菜单的显示/隐藏
    toggleDropdown () {
      if (!this.disabled) {
        this.isOpen = !this.isOpen;
      }
    },

    // 关闭下拉菜单
    closeDropdown () {
      this.isOpen = false;
    },

    // 选择选项
    selectOption (item) {
      if (this.multiple) {
        // 多选模式
        const currentValues = [...this.selectedValues];
        const index = currentValues.indexOf(item.value);

        if (index > -1) {
          // 取消选择
          currentValues.splice(index, 1);
        } else {
          // 添加选择
          currentValues.push(item.value);
        }

        this.$emit("update:modelValue", currentValues);
        this.$emit("change", currentValues);
        // 多选模式下不自动关闭下拉菜单
      } else {
        // 单选模式
        if (this.modelValue !== item.value) {
          this.$emit("update:modelValue", item.value);
          this.$emit("change", item.value);
        }
        this.closeDropdown();
      }
    },

    // 判断选项是否被选中（多选模式）
    isItemSelected (value) {
      if (!this.multiple) return false;
      return this.selectedValues.includes(value);
    },

    // 全选（多选模式）
    selectAll () {
      if (!this.multiple) return;
      const allValues = this.options.map((item) => item.value);
      this.$emit("update:modelValue", allValues);
      this.$emit("change", allValues);
    },

    // 清空选择（多选模式）
    clearAll () {
      if (!this.multiple) return;
      this.$emit("update:modelValue", []);
      this.$emit("change", []);
    },
  },
};
</script>

<style lang="less" scoped>
@primary-color: #4b58dc;
@transition-time: 0.3s;

.custom-dropdown {
  position: relative;
  // width: 100%;
  flex: 1;
  user-select: none;

  .dropdown-trigger {
    display: flex;
    align-items: center;
    justify-content: space-between;
    height: 40px;
    padding: 0 15px;
    background-color: #fff;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    cursor: pointer;
    transition: all @transition-time ease;
    position: relative;
    overflow: hidden;

    &:after {
      content: "";
      position: absolute;
      top: 0;
      left: -75%;
      width: 50%;
      height: 100%;
      background: linear-gradient(
        to right,
        rgba(255, 255, 255, 0),
        rgba(255, 255, 255, 0.4),
        rgba(255, 255, 255, 0)
      );
      transform: skewX(-15deg);
      transition: all 0.5s ease;
      opacity: 0;
    }

    &:hover {
      border-color: @primary-color;
      box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);

      &:after {
        left: 120%;
        opacity: 1;
      }
    }

    &.is-active {
      border-color: @primary-color;
      box-shadow: 0 0 0 2px rgba(75, 88, 220, 0.1);
      background: linear-gradient(
        to right,
        rgba(75, 88, 220, 0.02),
        rgba(255, 255, 255, 0.8),
        rgba(75, 88, 220, 0.02)
      );
    }

    &.is-disabled {
      background-color: #f5f7fa;
      border-color: #e4e7ed;
      color: #c0c4cc;
      cursor: not-allowed;
    }

    .selected-text {
      flex: 1;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      font-size: 14px;
      color: #606266;

      .placeholder {
        color: #c0c4cc;
      }

      .selected-info {
        color: @primary-color;
        font-weight: 500;
      }
    }

    .dropdown-icon {
      margin-left: 8px;
      color: #c0c4cc;
      transition: transform @transition-time ease;

      .arrow-down {
        width: 0;
        height: 0;
        border-left: 4px solid transparent;
        border-right: 4px solid transparent;
        border-top: 6px solid #c0c4cc;
        transition: transform @transition-time ease;

        &.is-rotate {
          transform: rotate(180deg);
        }
      }
    }
  }

  .dropdown-menu {
    position: absolute;
    top: calc(100% + 5px);
    left: 0;
    width: 100%;
    max-height: 200px;
    overflow-y: auto;
    background-color: #fff;
    border-radius: 4px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
    z-index: 10;
    animation: dropdown-in @transition-time ease;

    &::-webkit-scrollbar {
      width: 6px;
    }

    &::-webkit-scrollbar-thumb {
      background-color: #dcdfe6;
      border-radius: 3px;
    }

    &::-webkit-scrollbar-track {
      background-color: #f5f7fa;
    }

    .dropdown-toolbar {
      display: flex;
      justify-content: flex-end;
      align-items: center;
      gap: 10px;
      padding: 8px 15px;
      background: linear-gradient(
        to right,
        rgba(75, 88, 220, 0.05),
        rgba(255, 255, 255, 0.8),
        rgba(75, 88, 220, 0.05)
      );
      border-bottom: 1px solid #f0f0f0;
      font-size: 12px;

      .toolbar-btn {
        padding: 4px 8px;
        border-radius: 3px;
        cursor: pointer;
        transition: all @transition-time ease;
        color: #909399;

        &:hover {
          color: @primary-color;
          background-color: rgba(75, 88, 220, 0.1);
        }

        &.select-all {
          color: @primary-color;
        }

        &.clear-all {
          color: #f56c6c;
        }
      }
    }

    .dropdown-item {
      padding: 10px 15px;
      cursor: pointer;
      transition: all @transition-time ease;
      position: relative;
      overflow: hidden;

      &:after {
        content: "";
        position: absolute;
        top: 0;
        left: -75%;
        width: 50%;
        height: 100%;
        background: linear-gradient(
          to right,
          rgba(255, 255, 255, 0),
          rgba(255, 255, 255, 0.4),
          rgba(255, 255, 255, 0)
        );
        transform: skewX(-15deg);
        transition: all 0.5s ease;
        opacity: 0;
      }

      &:hover {
        background-color: rgba(75, 88, 220, 0.05);

        &:after {
          left: 120%;
          opacity: 1;
        }

        .item-label {
          color: @primary-color;
        }
      }

      &.is-active {
        background: linear-gradient(
          to right,
          rgba(75, 88, 220, 0.08),
          rgba(75, 88, 220, 0.02)
        );
        border-left: 3px solid @primary-color;

        .item-label {
          color: @primary-color;
          font-weight: 500;
        }
      }

      .item-content {
        display: flex;
        align-items: center;

        .item-dot {
          width: 18px;
          height: 18px;
          border-radius: 50%;
          border: 1px solid @primary-color;
          margin-right: 8px;
          display: flex;
          align-items: center;
          justify-content: center;
          background: #fff;

          .item-dot-inner {
            width: 10px;
            height: 10px;
            border-radius: 50%;
            background: linear-gradient(
              135deg,
              @primary-color,
              lighten(@primary-color, 20%)
            );
            animation: dot-scale 0.3s forwards;
          }
        }

        .item-checkbox {
          margin-right: 8px;

          .checkbox-wrapper {
            width: 16px;
            height: 16px;
            border: 1px solid #dcdfe6;
            border-radius: 2px;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: all @transition-time ease;
            background: #fff;

            &.is-checked {
              background: linear-gradient(
                135deg,
                @primary-color,
                lighten(@primary-color, 20%)
              );
              border-color: @primary-color;

              .check-mark {
                width: 8px;
                height: 4px;
                border-left: 2px solid #fff;
                border-bottom: 2px solid #fff;
                transform: rotate(-45deg);
                animation: check-scale 0.3s forwards;
              }
            }

            &:hover {
              border-color: @primary-color;
            }
          }
        }

        .item-label {
          font-size: 14px;
          color: #606266;
          transition: color @transition-time ease;
        }
      }
    }
  }
}

@keyframes dropdown-in {
  from {
    opacity: 0;
    transform: translateY(-10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes dot-scale {
  0% {
    transform: scale(0);
  }
  50% {
    transform: scale(1.2);
  }
  100% {
    transform: scale(1);
  }
}

@keyframes check-scale {
  0% {
    transform: scale(0) rotate(-45deg);
  }
  50% {
    transform: scale(1.2) rotate(-45deg);
  }
  100% {
    transform: scale(1) rotate(-45deg);
  }
}
</style>
